const connection = require('../app/database')

class CommentService {
    // 1.发表评论
    async create(momentId, content, userId) {
        try {
            const statement = `INSERT INTO comment (content,moment_id,user_id) VALUES (?,?,?);`
            const [result] = await connection.execute(statement, [content, momentId, userId])
            return result
        } catch (error) {
            console.log(error);
        }
    }

    // 2.回复评论
    async reply(momentId, content, userId, commentId) {
        try {
            const statement = `INSERT INTO comment (content,moment_id,user_id,comment_id) VALUES (?,?,?,?);`
            const [result] = await connection.execute(statement, [content, momentId, userId, commentId])
            return result
        } catch (error) {
            console.log(error);
        }
    }

    // 3.修改评论
    async update(commentId, content) {
        try {
            const statement = `UPDATE comment SET content = ? WHERE id = ?;`
            const [result] = await connection.execute(statement, [content, commentId])
            return result
        } catch (error) {
            console.log(error);
        }
    }

    // 4.删除评论
    async remove(commentId) {
        try {
            const statement = `DELETE FROM comment WHERE id = ?;`
            const [result] = await connection.execute(statement, [commentId])
            return result
        } catch (error) {
            console.log(error);
        }
    }

    // 5.获取评论
    async getCommentsByMomentId(momentId) {
        try {
            const statement = `SELECT m.id,m.content,m.comment_id commentId,m.createAt createTime,
                JSON_OBJECT('id',u.id,'name',u.name) user
                FROM comment m
                LEFT JOIN user u ON u.id=m.user_id
                WHERE moment_id = ?;`
            const [result] = await connection.execute(statement, [momentId])
            return result
        } catch (error) {
            console.log(error);
        }
    }
}

module.exports = new CommentService()